﻿using ALProtocol.Tcp;
using System.Text;
using System.Text.Unicode;

namespace Demo
{
    /// <summary>
    /// 定义演示的会话。 
    /// </summary>
    class DemoSession : TcpReading
    {
        internal  readonly TcpSession m_session;
        private bool m_autoReply = false;   // 是否自动回复。
        /// <summary>
        /// 
        /// </summary>
        /// <param name="session"></param>
        public DemoSession(TcpSession session, bool autoReply = false) : base(2000) // 演示，最大包2000字节。
        {
            m_session = session;
            session.Process(this);
            m_autoReply = autoReply;
        }
        /// <summary>
        /// 写入数据。
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool WriteData(string msg)
        {
            byte[] data = Encoding.UTF8.GetBytes(msg);
            var writing = new TcpWriting(data);
            writing.EndWrite += DoEnWrited;
            return m_session.Process(writing);
        }

        private void DoEnWrited(int len)
        {
            Console.WriteLine($"完成写入,{len}字节");
        }

        protected override int ProcData(byte[] buffer, int length)
        {
            var msg = Encoding.UTF8.GetString(buffer, 0, length);
            Console.WriteLine($"接收到{m_session.Remote.Port} 的数据:{msg}");
            //处理多少返回多少。
            if(m_autoReply)
            {
                WriteData($"服务端自动对{msg}的回复。");
            }
            return 0;
        }
    }
}
